package com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Store;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;
import com.huang825172.sbog.BaseFlux.Action.BaseAction;
import com.huang825172.sbog.BaseFlux.Store.BaseStore;
import com.huang825172.sbog.GlobalManager.LoginStateManager;
import com.huang825172.sbog.R;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Action.getVideoInfo;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Action.getVideoList;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Action.likeVideo;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Store.Datas.getVideoCommentReq;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Store.Datas.getVideoInfoReq;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Store.Datas.getVideoInfoRes;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Store.Datas.getVideoListReq;
import com.huang825172.sbog.Tabs.SoundAndExplore.VideoPage.Store.Datas.getVideoListRes;
import com.huang825172.sbog.Util.TAGs;
import com.huang825172.sbog.Util.VideoFileCacheManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class Store extends BaseStore{

    private LoginStateManager loginStateManager;
    private VideoFileCacheManager videoFileCacheManager;
    private ArrayList<VideoFileCacheManager.VideoItem> videoData;
    private getVideoInfoRes currentVideoInfo;

    public Store(Context context) {
        super(context);
        loginStateManager = new LoginStateManager(context);
        videoFileCacheManager = new VideoFileCacheManager(context);
        videoData = new ArrayList<>();
    }

    @Override
    public List<String> getActionLabels() {
        List<String> labels = new ArrayList<>();
        labels.add("VideoPageGetVideoListAction");
        labels.add("VideoPageGetVideoInfoAction");
        labels.add("VideoPageOpenShopAction");
        return labels;
    }

    @Override
    public void changeData(BaseAction action) {
        super.changeData(action);
        switch (action.getLabel()){
            case "VideoPageGetVideoListAction":{
                getVideoList act = (getVideoList)action;
                getVideoPage(act.getPage());
                break;
            }
            case "VideoPageGetVideoInfoAction":{
                getVideoInfo act = (getVideoInfo)action;
                getVideoInfo(act.getId());
                break;
            }
            case "VideoPageOpenShopAction":{
                notifyDataChanged("VideoPageOpenShopAction");
            }
            case "VideoPageLikeVideoAction": {
                likeVideo act = (likeVideo) action;
                LikeVideo(act.getId());
            }
            default:
                break;
        }
    }

    private void getVideoPage(int page){
        if(loginStateManager.getLoginToken()!= null && loginStateManager.getLoginPhone() != null) {
            final Gson gson = new Gson();
            getVideoListReq info = new getVideoListReq(loginStateManager.getLoginToken(),page);
            final String infoStr = gson.toJson(info);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(context.getString(R.string.server_baseUrl))
                    .build();
            Interfaces request = retrofit.create(Interfaces.class);
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), infoStr);
            Call<ResponseBody> call = request.getVideoList(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(final Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resStr = response.body().string();
                        getVideoListRes resObj = gson.fromJson(resStr, getVideoListRes.class);
                        if (resObj.code == 200){
                            for(int i = 0; i<resObj.data.size(); i++){
                                int id = resObj.data.get(i).id;
                                String url = resObj.data.get(i).url;
                                if(getExt(url).equals("mp4")) {
                                    videoData.add(videoFileCacheManager.new VideoItem(id, url));
                                }
                            }
                            notifyDataChanged("VideoPageGetListSuccess");
                        }else {
                            notifyDataChanged("VideoPageGetListFail");
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                        Log.e(TAGs.ERROR, e.getMessage());
                        notifyDataChanged("VideoPageGetListFail");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    t.printStackTrace();
                    Log.e(TAGs.ERROR, t.getMessage());
                    notifyDataChanged("VideoPageGetListFail");
                }
            });
        }
    }

    private void getVideoInfo(int id){
        if(loginStateManager.getLoginToken()!= null && loginStateManager.getLoginPhone() != null) {
            final Gson gson = new Gson();
            getVideoInfoReq info = new getVideoInfoReq(loginStateManager.getLoginToken(),id);
            final String infoStr = gson.toJson(info);
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(context.getString(R.string.server_baseUrl))
                    .build();
            Interfaces request = retrofit.create(Interfaces.class);
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), infoStr);
            Call<ResponseBody> call = request.getVideoInfo(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(final Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resStr = response.body().string();
                        getVideoInfoRes resObj = gson.fromJson(resStr, getVideoInfoRes.class);
                        if (resObj.code == 200){
                            currentVideoInfo = resObj;
                            notifyDataChanged("VideoPageGetInfoSuccess");
                        }else {
                            notifyDataChanged("VideoPageGetInfoFail");
                        }
                    } catch (Exception e){
                        e.printStackTrace();
                        Log.e(TAGs.ERROR, e.getMessage());
                        notifyDataChanged("VideoPageGetInfoFail");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    t.printStackTrace();
                    Log.e(TAGs.ERROR, t.getMessage());
                    notifyDataChanged("VideoPageGetInfoFail");
                }
            });

            getVideoCommentReq commentInfo = new getVideoCommentReq(loginStateManager.getLoginToken(), id);
            final String commentInfoStr = gson.toJson(commentInfo);
            RequestBody commentBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), commentInfoStr);
            Call<ResponseBody> commentCall = request.getVideoComment(body);
            commentCall.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resStr = response.body().string();
                        Log.d(TAGs.INFO, resStr);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAGs.ERROR, e.getMessage());
                        notifyDataChanged("VideoPageGetCommentFail");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    t.printStackTrace();
                    Log.e(TAGs.ERROR, t.getMessage());
                    notifyDataChanged("VideoPageGetCommentFail");
                }
            });
        }
    }

    private void LikeVideo(int id) {
        likeVideo info = new likeVideo(id);
        // 省略一万行请求代码
        // 我去整理下代码吧
        // 明天满课
        // 整理完就这么交了
        // sbOg 再见
    }

    public static File getParentFile(@NonNull Context context) {
        final File externalSaveDir = context.getExternalCacheDir();
        if (externalSaveDir == null) {
            return context.getCacheDir();
        } else {
            return externalSaveDir;
        }
    }

    public String getVideo(int index){
        return videoFileCacheManager.getVideo(index);
    }

    public ArrayList<VideoFileCacheManager.VideoItem> getVideoData() {
        return videoData;
    }

    public static String getExt(String filename) {
        int index = filename.lastIndexOf(".");

        if (index == -1) {
            return null;
        }
        String result = filename.substring(index + 1);
        return result;
    }

    public getVideoInfoRes getCurrentVideoInfo() {
        return currentVideoInfo;
    }
}
